package com.carpedil.movie.service.impl;

import com.alibaba.fastjson.JSON;
import com.carpedil.common.dto.OrderDTO;
import com.carpedil.util.StringUtil;
import org.springframework.stereotype.Service;

import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/** @author Administrator */
@Service
@ServerEndpoint("/orderHandler")
public class MovieSocketService {
  List<Session> sessionList = new ArrayList<>();

  @OnOpen
  public void onopen(Session session) {
    System.out.println("------------连接成功--------------");
    sessionList.add(session);
  }

  @OnMessage
  public void sendMessage(String msg, Session session) throws IOException {
    System.out.println(msg);
    System.out.println("------------发送消息--------------");
    while (true) {
      for (Session s : this.sessionList) {
        if (null != session && session.isOpen()) {
          // 获取内存中list数据
          List<OrderDTO> list = StringUtil.list;
          if (!list.isEmpty()) {
            // 将list数据转换为json格式的字符串
            String jsonString = JSON.toJSONString(list);
            try {
              System.out.println("jsonString = " + jsonString);
              s.getBasicRemote().sendText(jsonString);
            } catch (IOException e) {
              e.printStackTrace();
            }
          }
        }
        try {
          Thread.sleep(200);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    }
  }
}
